package com.cuitrip.business.tripservice;

import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.cuitrip.business.location.map.GaoDeMapActivity;
import com.cuitrip.business.tripservice.event.ServiceChangeEvent;
import com.cuitrip.business.tripservice.model.FormType;
import com.cuitrip.business.tripservice.model.OtherNotes;
import com.cuitrip.business.tripservice.model.ServiceInfo;
import com.cuitrip.business.tripservice.ui.EditDetailLayout;
import com.cuitrip.component.item.ItemLayout;
import com.cuitrip.component.para.model.Para;
import com.cuitrip.component.para.proxy.ParaProxy;
import com.cuitrip.service.R;
import com.cuitrip.util.GaoDeMapController;
import com.cuitrip.util.GoogleMapController;
import com.cuitrip.util.MapController;
import com.cuitrip.util.MapUtil;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragment;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.rx.bus.RxBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by sheena on 16/4/26.
 */
public class CreateTripOtherInfoFragment extends CustomUiFragment {
    public final static int ATTENTION_TYPE = 0x01;
    public final static int SAFE_TIPS_TYPE = 0x05;
    public final static int CLOTH_TIPS_TYPE = 0x03;
    public final static int WEATHER_TIPS_TYPE = 0x04;
    public final static int LOCATION_TYPE = 0x06;
    public static final String OTHER_NOTE_KEY = "othernotes";
    public static final String ATTENTION_KEY = "attention_key";
    public static final String SAFE_KEY = "safe_key";
    public static final String CLOTH_KEY = "cloth_key";
    public static final String WEATHER_KEY = "weather_key";
    public static final String EDIT_KEY = "edit";
    private final static int TEXT_MAX_LIMIT = 500;
    @Bind(R.id.order_location)
    protected ItemLayout mOrderLocation;
    @Bind(R.id.trip_attention)
    protected EditDetailLayout mTripAttention;
    @Bind(R.id.trip_safe_tips)
    protected EditDetailLayout mTripSafeTips;
    @Bind(R.id.trip_clothes_tips)
    protected EditDetailLayout mTripClothTips;
    @Bind(R.id.trip_weather_tips)
    protected EditDetailLayout mTripWeatherTips;
    boolean useGoogleMap = false;
    MapController controller;
    private HashMap<Integer, ArrayList<CharSequence>> paraListArray = new HashMap<>();
    private OtherNotes mOtherNotes;
    private boolean isEdit = false;
    private ServiceInfo serviceInfo;
    private double longitude;
    private double latitude;
    AMapLocationListener listener = new AMapLocationListener() {



        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getCountry() != null && amapLocation.getCountry().equals("中国")) {
                    useGoogleMap = false;
                    if (amapLocation.getProvince() != null && amapLocation.getProvince().contains("台湾") || amapLocation.getProvince().contains("香港")
                            || amapLocation.getProvince().contains("澳门")) {
                        useGoogleMap = true;
                    }
                } else {
                    useGoogleMap = true;
                }
                latitude = amapLocation.getLatitude();
                longitude = amapLocation.getLongitude();

            }
            hideLoading();
            //加载地图Fragment
            if (MapUtil.isGmsAvailable() && (useGoogleMap || MapUtil.debugGoogleMap())) {
                controller = new GoogleMapController();
            } else {
                controller = new GaoDeMapController();
            }
            controller.init(getHostActivity(), serviceInfo.getMeetingPlace(), serviceInfo.getLat(), serviceInfo.getLng());
        }

        @Override
        public void onLocationChanged(Location location) {

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };
    private LocationManagerProxy mLocationManagerProxy;

    public static CreateTripOtherInfoFragment newInstance(ServiceInfo serviceInfo, boolean isEdit) {
        CreateTripOtherInfoFragment createTripOthersFragment = new CreateTripOtherInfoFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(ServiceInfo.KEY, serviceInfo);
        bundle.putBoolean(EDIT_KEY, isEdit);
        createTripOthersFragment.setArguments(bundle);
        return createTripOthersFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState, R.layout.page_other_instruction);
        if (getArguments() != null) {
            serviceInfo = (ServiceInfo) getArguments().getSerializable(ServiceInfo.KEY);
            isEdit = getArguments().getBoolean(EDIT_KEY);
            mOtherNotes = serviceInfo.getOtherNotes();
        }
        return view;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this, getView());
        initNavigation();
        mTripAttention.showRightHint(true);
        mTripSafeTips.showRightHint(true);
        mTripClothTips.showRightHint(true);
        mTripWeatherTips.showRightHint(true);
        initTitle();
        initMap();

    }

    @Override
    public void initData() {
        initValue();
        initValue(ATTENTION_TYPE, SAFE_TIPS_TYPE, CLOTH_TIPS_TYPE, WEATHER_TIPS_TYPE);
    }

    private void initTitle() {
        mTripAttention.setTitle(getString(R.string.trip_attribute_advice));
        mTripClothTips.setTitle(getString(R.string.trip_attribute_outfit));
        mTripWeatherTips.setTitle(getString(R.string.trip_attribute_weather));
        mTripSafeTips.setTitle(getString(R.string.trip_attribute_safety));
    }

    private void initValue(int... contentTypes) {
        for (int contentType : contentTypes) {
            initTypeValue(contentType);
        }
    }

    private void initTypeValue(int contentType) {
        switch (contentType) {
            case SAFE_TIPS_TYPE:
                if (TextUtils.isEmpty(mOtherNotes.getServiceSafeTips()) && !isEdit) {
                    mTripSafeTips.setVisibility(View.GONE);
                } else {
                    ArrayList<CharSequence> stringArray = ParaProxy.getInstance().getParaList(mOtherNotes.getServiceSafeTips());
                    setValueInContent(SAFE_TIPS_TYPE, stringArray);
                }
                break;
            case ATTENTION_TYPE:
                if (TextUtils.isEmpty(mOtherNotes.getServiceNotice()) && !isEdit) {
                    mTripAttention.setVisibility(View.GONE);
                } else {
                    ArrayList<CharSequence> stringArray = ParaProxy.getInstance().getParaList(mOtherNotes.getServiceNotice());
                    setValueInContent(ATTENTION_TYPE, stringArray);
                }
                break;
            case CLOTH_TIPS_TYPE:
                if (TextUtils.isEmpty(mOtherNotes.getServiceWearTips()) && !isEdit) {
                    mTripClothTips.setVisibility(View.GONE);
                } else {
                    ArrayList<CharSequence> stringArray = ParaProxy.getInstance().getParaList(mOtherNotes.getServiceWearTips());
                    setValueInContent(CLOTH_TIPS_TYPE, stringArray);
                }
                break;
            case WEATHER_TIPS_TYPE:
                if (TextUtils.isEmpty(mOtherNotes.getUnexpectedWeather()) && !isEdit) {
                    mTripWeatherTips.setVisibility(View.GONE);
                } else {
                    ArrayList<CharSequence> stringArray = ParaProxy.getInstance().getParaList(mOtherNotes.getUnexpectedWeather());
                    setValueInContent(WEATHER_TIPS_TYPE, stringArray);
                }
            case LOCATION_TYPE:
                if (!TextUtils.isEmpty(serviceInfo.getMeetingPlace())) {
                    mOrderLocation.setmRightText(serviceInfo.getMeetingPlace());
                }
                break;
        }
    }

    private void initNavigation() {
        mTripAttention.setNavigateAction(new EditDetailLayout.NavigateAction() {
            @Override
            public void navigate() {
                Intent intent = new Intent(getContext(), ParaEditActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString(ParaEditActivity.TITLE_KEY, getString(R.string.trip_attribute_advice));
                if (paraListArray.get(ATTENTION_TYPE) != null) {
                    bundle.putCharSequenceArrayList(ParaEditActivity.PARA_KEY, paraListArray.get(ATTENTION_TYPE));
                }
                bundle.putInt(ParaEditActivity.MAX_LIMIT_KEY, TEXT_MAX_LIMIT);
                intent.putExtras(bundle);
                startActivityForResult(intent, ATTENTION_TYPE);
            }
        });

        mTripSafeTips.setNavigateAction(new EditDetailLayout.NavigateAction() {
            @Override
            public void navigate() {
                Intent intent = new Intent(getContext(), ParaEditActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString(ParaEditActivity.TITLE_KEY, getString(R.string.trip_attribute_safety));
                if (paraListArray.get(SAFE_TIPS_TYPE) != null) {
                    bundle.putCharSequenceArrayList(ParaEditActivity.PARA_KEY, paraListArray.get(SAFE_TIPS_TYPE));
                }
                bundle.putInt(ParaEditActivity.MAX_LIMIT_KEY, TEXT_MAX_LIMIT);
                intent.putExtras(bundle);
                startActivityForResult(intent, SAFE_TIPS_TYPE);
            }
        });

        mTripClothTips.setNavigateAction(new EditDetailLayout.NavigateAction() {
            @Override
            public void navigate() {
                Intent intent = new Intent(getContext(), ParaEditActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString(ParaEditActivity.TITLE_KEY, getString(R.string.trip_attribute_outfit));
                if (paraListArray.get(CLOTH_TIPS_TYPE) != null) {
                    bundle.putCharSequenceArrayList(ParaEditActivity.PARA_KEY, paraListArray.get(CLOTH_TIPS_TYPE));
                }
                bundle.putInt(ParaEditActivity.MAX_LIMIT_KEY, TEXT_MAX_LIMIT);
                intent.putExtras(bundle);
                startActivityForResult(intent, CLOTH_TIPS_TYPE);
            }
        });

        mTripWeatherTips.setNavigateAction(new EditDetailLayout.NavigateAction() {
            @Override
            public void navigate() {
                Intent intent = new Intent(getContext(), ParaEditActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString(ParaEditActivity.TITLE_KEY, getString(R.string.trip_attribute_weather));
                if (paraListArray.get(WEATHER_TIPS_TYPE) != null) {
                    bundle.putCharSequenceArrayList(ParaEditActivity.PARA_KEY, paraListArray.get(WEATHER_TIPS_TYPE));
                }
                bundle.putInt(ParaEditActivity.MAX_LIMIT_KEY, TEXT_MAX_LIMIT);
                intent.putExtras(bundle);
                startActivityForResult(intent, WEATHER_TIPS_TYPE);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            ArrayList<String> highList = data.getStringArrayListExtra(ParaEditActivity.PARA_KEY);
            setValueInContent(requestCode, highList);
        }
        if (requestCode == GaoDeMapActivity.REQUEST) {
            if (data != null) {
                String meetingPlace = GaoDeMapActivity.getName(data);
                String latitude = String.valueOf(GaoDeMapActivity.getLat(data));
                String longitude = String.valueOf(GaoDeMapActivity.getLng(data));
                serviceInfo.setMeetingPlace(meetingPlace);
                serviceInfo.setLat(latitude);
                serviceInfo.setLng(longitude);
            }
        }
        if (requestCode == GoogleMapController.PLACE_PICKER_REQUEST) {
            if (data == null) {
                return;
            }
            Place place = PlacePicker.getPlace(data, getContext());
            String meetingPlace = place.getName().toString();
            String latitude = String.valueOf(place.getLatLng().latitude);
            String longitude = String.valueOf(place.getLatLng().longitude);
            serviceInfo.setMeetingPlace(meetingPlace);
            serviceInfo.setLat(latitude);
            serviceInfo.setLng(longitude);
        }
        bindMeetingPlace();
    }

    private void setValueInContent(int contentType, Object value) {
        switch (contentType) {
            case ATTENTION_TYPE:
                setValueToLayout(mTripAttention, contentType, value);
                break;
            case CLOTH_TIPS_TYPE:
                setValueToLayout(mTripClothTips, contentType, value);
                break;
            case WEATHER_TIPS_TYPE:
                setValueToLayout(mTripWeatherTips, contentType, value);
                break;
            case SAFE_TIPS_TYPE:
                setValueToLayout(mTripSafeTips, contentType, value);
                break;
        }
    }

    private void setValueToLayout(EditDetailLayout editDetailLayout, int type, Object value) {
        List<Para> paraList = new ArrayList<>();
        if (value instanceof List) {
            ArrayList<CharSequence> valueList = (ArrayList<CharSequence>) value;
            for (CharSequence charSequence : valueList) {
                Para para = new Para(charSequence);
                paraList.add(para);
            }
            paraListArray.put(type, valueList);
        } else {
            paraListArray.remove(type);
        }
        editDetailLayout.setParaList(paraList);
    }

    /**
     * 初始化 AMap 对象
     */
    private void initMap() {
        showLoading();
        //获取位置信息
        mLocationManagerProxy = LocationManagerProxy.getInstance(AppCoreRuntime.context);
        //此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        //注意设置合适的定位时间的间隔，并且在合适时间调用removeUpdates()方法来取消定位请求
        //在定位结束后，在合适的生命周期调用destroy()方法
        //其中如果间隔时间为-1，则定位只定一次
        mLocationManagerProxy.requestLocationData(
                LocationProviderProxy.AMapNetwork, -1, 1000, listener);
        mLocationManagerProxy.setGpsEnable(false);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mLocationManagerProxy.destroy();

    }

    @OnClick(R.id.order_location)
    public void setMeetLocation() {
        if (!"0".equals(serviceInfo.getLat()) && !"0".equals(serviceInfo.getLng())){
            MapUtil.getDefaultInstance().searchMap(this, serviceInfo.getLat(), serviceInfo.getLng(), serviceInfo.getMeetingPlace());
        }else{
            MapUtil.getDefaultInstance().searchMap(this, String.valueOf(latitude), String.valueOf(longitude), " ");
        }
    }

    private void bindMeetingPlace() {
        mOrderLocation.setmRightText(serviceInfo.getMeetingPlace());
    }


    private void saveAction() {
        ArrayList<CharSequence> attentionList = paraListArray.get(ATTENTION_TYPE);
        ArrayList<CharSequence> safeList = paraListArray.get(SAFE_TIPS_TYPE);
        ArrayList<CharSequence> clothList = paraListArray.get(CLOTH_TIPS_TYPE);
        ArrayList<CharSequence> weatherList = paraListArray.get(WEATHER_TIPS_TYPE);
        serviceInfo.getOtherNotes().setServiceNotice(ParaProxy.getInstance().outputPara(attentionList));
        serviceInfo.getOtherNotes().setServiceSafeTips(ParaProxy.getInstance().outputPara(safeList));
        serviceInfo.getOtherNotes().setServiceWearTips(ParaProxy.getInstance().outputPara(clothList));
        serviceInfo.getOtherNotes().setUnexpectedWeather(ParaProxy.getInstance().outputPara(weatherList));
        RxBus.getDefault().send(new ServiceChangeEvent(FormType.OTHERS));
    }


    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mTopbarLeftAreaName = getString(R.string.back_icon);
        config.mTopbarMiddleAreaName = getString(R.string.trip_group_additional_info);
        return config;
    }

    @Override
    public void onTopbarLeftPress() {
        onBackPressed(false);
    }

    @Override
    public boolean onBackPressed(boolean fromKey) {
        saveAction();
        return super.onBackPressed(fromKey);
    }

}
